package com.dy.security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.security.entity.UsersEntity;
import com.dy.security.mapper.UsersMapper;
import com.dy.security.service.UsersService;
import com.dy.sucetity.exception.BadRequestException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:
 * @Author: dingyu
 * @Desctiption: (描述)
 * @Date: 2022/3/30 17:28
 * @Version 1.0 (版本)
 */
@Service
public class UserServiceImpl extends ServiceImpl<UsersMapper, UsersEntity> implements UsersService, UserDetailsService {

    private static final String USER_NOT_EXIST="当前用户不存在呀";

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.查看用户是否存在
        UsersEntity users = baseMapper.getUsers(username);
        if (ObjectUtils.isEmpty(users)) {
            throw new BadRequestException(USER_NOT_EXIST);
        }
        //数据库形式的roles解析为UserDetails权限集
        //AuthorityUtils.commaSeparatedStringToAuthorityList() spring提供方法，从逗号隔开返回权限集
        //1.逗号分割
        users.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(users.getRoles()));
        //2.自定义方法generateAuthorities使用';'分割
        /**
        users.setAuthorities(this.generateAuthorities(users.getRoles()));
         **/
        return users;
    }

    /**
     * 自定义解析数据库roles为UserDetails权限集
     * @param roles 数据库角色
     * @return List<GrantedAuthority>
     */
    private List<GrantedAuthority> generateAuthorities(String roles){
        String[] strings = StringUtils.tokenizeToStringArray(roles, ";");
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(strings.length);
        for (String authority : strings) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority));
        }

        return grantedAuthorities;
    }
}
